<!--
 * @Author: Wang WeiHao
 * @Date: 2024-09-26 14:42:55
 * @LastEditors: Wang WeiHao
 * @LastEditTime: 2024-10-21 14:35:43
 * @Description: 
 * @FilePath: \geo-base-dm\src\views\main\ai-analysis\left_popup.vue
-->
<template>
	<div class="ai-popup" :class="isHidden ? 'hidden-pannel' : ''">
		<!-- sho解译任务提交框 -->
		<!-- <popupBox title="统计分析" @close="closePopup" /> -->
		<div class="hidden-btn" @click="isHidden = !isHidden"></div>

		<div class="form-container">
			<el-form ref="formRef" label-position="top" label-width="100px" :model="aiTaskFormData">
				<el-form-item label="分屏对比分析:">
					<div>{{ currentTiff }}</div>
				</el-form-item>
				<el-form-item label="左视图图层:">
					<el-tree-select
						:data="vetorlist"
						v-model="firstchooseVector"
						placeholder="请选择"
						size="small"
						style="width: 240px"
						:props="{
							label: 'fileName', // 使用 fileName 作为标签显示字段
							children: 'children', // 子节点的字段名
						}"
					>
						<!-- <el-option
							v-for="item in vetorlist"
							:key="item.id"
							:label="item.fileName"
							:value="item.id"
						/> -->
					</el-tree-select>
				</el-form-item>
				<el-form-item label="右视图图层:">
					<!-- <el-select
						v-model="secondchooseVector"
						placeholder="请选择"
						size="small"
						style="width: 240px"
					>
						<el-option
							v-for="item in vetorlist"
							:key="item.id"
							:label="item.fileName"
							:value="item.id"
						/>
					</el-select> -->
					<el-tree-select
						:data="vetorlist"
						v-model="secondchooseVector"
						placeholder="请选择"
						size="small"
						style="width: 240px"
						:props="{
							label: 'fileName', // 使用 fileName 作为标签显示字段
							children: 'children', // 子节点的字段名
						}"
					>
					</el-tree-select>
				</el-form-item>

				<div class="bottom-btn-group">
					<el-button
						class="elBtn"
						@click="createTask(formRef)"
						v-loading.fullscreen.lock="fullscreenLoading"
					>
						分析
					</el-button>
					<!-- <el-button class="elBtn" @click="closePopup"> 重置 </el-button> -->
					<el-button class="elBtn" @click="countChart(formRef)"> 统计图表 </el-button>
				</div>
				<!-- <div class="bottom-btn-group">
				</div> -->
			</el-form>
		</div>
	</div>
	<el-dialog v-model="resultDialog" title="分析结果" width="1100px" append-to-body>
		<div>
			<analysisResult :chartsData="chartsData" :vectitle="vectitle" />
		</div>
	</el-dialog>
	<el-dialog v-model="testingDialog" title="正在分析" width="300px" append-to-body>
		<div></div>
	</el-dialog>
</template>

<script setup lang="ts">
// import popupBox from "@cps/popupBox/index.vue";
import { addTask, shpGeo } from "@/api/ai-processing";
import analysisResult from "./analysisResult.vue";
import mapTool from "@/utils/maptools/map";
import { ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";
import { useTaskStore, useUserStore } from "@/store";
import {
	queryOptionById,
	analysByShp,
	getCountColumn,
	getShpService,
} from "@/api/data-management/index";
import {
	getUserFileList,
	getUserFileDetail,
	getcountTable,
	getAnalysisResult,
} from "@/api/data-management/index";
import type { taskListItem, dataListItem, Tree } from "@/api/ai-processing/types";
import { id } from "element-plus/es/locale";
import { title } from "process";
import { polygonToLineString } from "@turf/turf";
// import analysResult from "./analysResult.vue";
let base_config = BASE_CONFIG;
const isHidden = ref(false);
const formRef = ref<FormInstance>();
const taskStore = useTaskStore();
const popupShow = computed(() => taskStore.shpPopshow);
const currentTiff = computed(() => taskStore.taskInfo?.fileName);
const currentArea = computed(() => taskStore.taskInfo?.geo);
interface Option {
	value: string;
	label: string;
}
onMounted(() => {
	console.log(taskStore.taskInfo);
});
const chartsData = ref([]);
const resultDialog = ref(false);
const testingDialog = ref(false);
const fullscreenLoading = ref(false);
const sortField = ref("");
const countField = ref("");
const countType = ref("1");
const statisticsOptions = ref([
	{
		value: "1",
		label: "求和",
	},
]);
const countTypeOptions = ref([
	// {
	// 	value: "SHAPE_Area",
	// 	label: "SHAPE_Area",
	// },
]);
const classifyOptions = ref([] as Option[]);
watch(
	() => taskStore.taskInfo?.id,
	(newId: any) => {
		if (newId && taskStore.taskInfo?.type != "1") {
			queryOptionById(newId).then((res) => {
				if (res.code === 200) {
					classifyOptions.value = res.data.map((key: any) => {
						return {
							value: key,
							label: key,
						};
					});
					sortField.value = res.data[0];
					// countField.value = res.data[1];
				}
			});
			getCountColumn(newId).then((res) => {
				if (res.code === 200) {
					countTypeOptions.value = res.data.map((key: any) => {
						return {
							value: key,
							label: key,
						};
					});
					countField.value = res.data[0];
				}
			});
		}
	},
	{ immediate: true } // 立即执行一次，以防初始时 id 已存在
);

// 解译任务创建弹窗 更新1
const aiTaskFormData: {
	type: string[];
	region: number;
	taskName: string;
} = reactive({
	type: [],
	region: 3,
	taskName: "",
});
watch(currentTiff, (newV) => {
	aiTaskFormData.taskName = newV || "";
});

const closePopup = () => {
	firstchooseVector.value = "";
	secondchooseVector.value = "";
	// mapTool.removeAllLayersExceptBase("ai-interpretation");
	// mapTool.removeAllLayersExceptBase("ai-interpretation1");
	mapTool.removeAllSlicingLayer("ai-interpretation");
	setTimeout(() => {
		// mapTool.removeAllSlicingLayer("ai-interpretation1");
	}, 500);
};
const isSarWater = ref(false);
// todo 创建解译任务
const createTask = async (formEl: FormInstance | undefined) => {
	fullscreenLoading.value = true;
	mapTool.clearVectorLayer("ai-interpretation");
	mapTool.clearVectorLayer("ai-interpretation1");
	let res = await getAnalysisResult(firstchooseVector.value, secondchooseVector.value);
	let json = res.data;
	setTimeout(() => {
		fullscreenLoading.value = false;
	}, 20);
	mapTool.addjsonFeature("ai-interpretation", json);
	mapTool.addjsonFeature("ai-interpretation1", json);
};
const vectitle = ref([]);
const countChart = async (formEl: FormInstance | undefined) => {
	let res = await getcountTable(firstchooseVector.value, secondchooseVector.value);
	chartsData.value = res.data.data;
	vectitle.value = res.data.title;
	resultDialog.value = true;
};
// todo 切换面积方式
const currentGeo: Ref<string | undefined> = ref();
// 已绘制的要素
let currentFeature: any;

// 地图业务,清除画笔交互
const clearDraw = () => {
	mapTool.vectorLayerList["ai-interpretation"]?.getSource()?.removeFeature(currentFeature);
	mapTool.removeDrawInteraction("ai-interpretation");
};
const userStore = useUserStore();
const getUserCode = computed(() => userStore.userCode);
const vetorlist = ref([] as any);
const firstchooseVector = ref("");
const secondchooseVector = ref("");
const findItemById = (list: any, targetId: any) => {
	for (let item of list) {
		// 如果当前项的 id 匹配，返回该项
		if (item.id === targetId) {
			return item;
		}

		// 如果有子项，递归查找子项
		if (item.children && item.children.length > 0) {
			const foundItem = findItemById(item.children, targetId);
			if (foundItem) {
				return foundItem; // 如果在子项中找到了，返回该项
			}
		}
	}
	return null; // 如果没有找到，返回 null
};
watch(firstchooseVector, (newV) => {
	// let item = vetorlist.value.find((item: any) => item.id == newV);
	const item = findItemById(vetorlist.value, newV);
	console.log(newV);
	taskStore.setInfo({
		rightLegendShow: newV ? true : false,
	});
	if (newV) {
		showTiff(item, "ai-interpretation");
	} else {
		// mapTool.removeSlicingLayer("ai-interpretation", item.filePath);
	}
});
watch(secondchooseVector, (newV) => {
	// let item = vetorlist.value.find((item: any) => item.id == newV);
	const item = findItemById(vetorlist.value, newV);
	console.log(newV);
	taskStore.setInfo({
		leftLegendShow: newV ? true : false,
	});
	if (newV) {
		showTiff(item, "ai-interpretation1");
	} else {
		// mapTool.removeAllSlicingLayer("ai-interpretation1");
	}
});
const showTiff = async (item: dataListItem, mindex: string, forceShow = false) => {
	// todo 这里可以加上判断，如果已经在area里面了，就不进行locationByWkt定位
	console.log(item);
	taskStore.setInfo({
		viewftp: item,
	});
	let res = await getUserFileDetail(item.id);
	if (mapTool.hasSlicingLayer(mindex, res.data.filePath)) {
		// mapTool.clearVectorLayer("ai-interpretation");
		if (!forceShow) {
			mapTool.removeAllSlicingLayer(mindex);
		}
	} else {
		// mapTool.clearVectorLayer("ai-interpretation");
		mapTool.removeAllSlicingLayer(mindex);
		if (item.type == "1") {
			mapTool.locationByWkt(mindex, res.data.geo);
			mapTool.addSlicingLayer(mindex, res.data.filePath);
		} else {
			mapTool.locationByBbox(mindex, res.data.bbox);
			mapTool.addSlicingWFSLayer(mindex, res.data.shpServiceUrl, res.data.tableName);
			// mapTool.addSlicingLayer("ai-interpretation", res.data.filePath);
		}
	}
	return res;
};
onMounted(async () => {
	if (typeof getUserCode.value === "undefined") {
		ElMessage({
			message: "请先登录",
			type: "error",
		});
		return;
	}
	let res = await getShpService(getUserCode.value, true, "");
	vetorlist.value = res.data;
	// vetorlist.value = [
	// 	{
	// 		value: "1",
	// 		label: "test",
	// 		id: 1,
	// 		children: [
	// 			{
	// 				value: "1-1",
	// 				label: "矢量数据",
	// 				id: 2,
	// 				children: [
	// 					{
	// 						value: 10006976,
	// 						label: "ld420325.shp",
	// 						id: 10006976,
	// 						fileName: "ld420325.shp",
	// 						fileMd5: "A136400154C1BE158040D4A6F9372878",
	// 						filePath:
	// 							"W:\\e188ecd6-1a27-4d7a-a6a3-ff01cec41fd2\\test\\矢量数据\\ld420325\\ld420325.shp",
	// 						fileSize: "59Mb",
	// 						uploadStatus: 1,
	// 						createTime: "2024-11-13T09:59:46.000+08:00",
	// 						updateTime: "2024-11-13T09:59:46.000+08:00",
	// 						err: null,
	// 						ip: "113.57.78.23",
	// 						type: "2",
	// 						shpServiceUrl: "http://113.57.78.20:38041/geoserver/decode/wms",
	// 						tableName: "vector:vector20241113095956",
	// 						bbox: "[110.04416244518679,31.55977898458982,111.25253672052355,32.51109209015127]",
	// 						zipFilePath: "W:\\e188ecd6-1a27-4d7a-a6a3-ff01cec41fd2\\test\\矢量数据\\ld420325.zip",
	// 						woodField: "ld2020",
	// 						legendUrl:
	// 							"E:\\\\project\\\\superai\\\\legend\\\\output\\f49439c6-1e4d-457d-a327-e71eb1617ddb.png",
	// 					},
	// 					{
	// 						value: 10006977,
	// 						label: "Id422801_2022.shp",

	// 						id: 10006977,
	// 						fileName: "ld20325_2022.shp",
	// 						fileMd5: "81C1D51F7107E6B6F400B430C96D5E8C",
	// 						filePath:
	// 							"W:\\e188ecd6-1a27-4d7a-a6a3-ff01cec41fd2\\test\\矢量数据\\ld20325_2022\\ld20325_2022.shp",
	// 						fileSize: "59Mb",
	// 						uploadStatus: 1,
	// 						createTime: "2024-11-13T10:07:48.000+08:00",
	// 						updateTime: "2024-11-13T10:07:48.000+08:00",
	// 						err: null,
	// 						ip: "113.57.78.23",
	// 						type: "2",
	// 						shpServiceUrl: "http://113.57.78.20:38041/geoserver/decode/wms",
	// 						tableName: "vector:vector20241113100758",
	// 						bbox: "[110.04416244518636,31.559778984231503,111.25253672052487,32.511092088909514]",
	// 						zipFilePath:
	// 							"W:\\e188ecd6-1a27-4d7a-a6a3-ff01cec41fd2\\test\\矢量数据\\ld20325_2022.zip",
	// 						woodField: "ld2022",
	// 						legendUrl:
	// 							"E:\\\\project\\\\superai\\\\legend\\\\output\\29769abb-26ef-4fcf-bb1f-261551e10425.png",
	// 					},
	// 					{
	// 						value: 10006978,
	// 						label: "Id422801_2022.shp",
	// 						id: 10006978,
	// 						fileName: "ld422801.shp",
	// 						fileMd5: "E33EF1DC7D1D6DFF6CE7CC499E85A833",
	// 						filePath:
	// 							"W:\\e188ecd6-1a27-4d7a-a6a3-ff01cec41fd2\\test\\矢量数据\\Id422801\\ld422801.shp",
	// 						fileSize: "199Mb",
	// 						uploadStatus: 1,
	// 						createTime: "2024-11-13T10:14:31.000+08:00",
	// 						updateTime: "2024-11-13T10:14:31.000+08:00",
	// 						err: null,
	// 						ip: "113.57.78.23",
	// 						type: "2",
	// 						shpServiceUrl: "http://113.57.78.20:38041/geoserver/decode/wms",
	// 						tableName: "vector:vector20241113101440",
	// 						bbox: "[109.0856938851628,29.851317970170662,109.97971058526335,30.670416019798306]",
	// 						zipFilePath: "W:\\e188ecd6-1a27-4d7a-a6a3-ff01cec41fd2\\test\\矢量数据\\Id422801.zip",
	// 						woodField: "ld2020",
	// 						legendUrl:
	// 							"E:\\\\project\\\\superai\\\\legend\\\\output\\9ab76e94-b677-4c00-95ae-9be09f99f6d9.png",
	// 					},
	// 					{
	// 						value: 10006979,
	// 						label: "Id422801_2022.shp",
	// 						id: 10006979,
	// 						fileName: "Id422801_2022.shp",
	// 						fileMd5: "9DB8079A202F269D6486C4B00D9A06EB",
	// 						filePath:
	// 							"W:\\e188ecd6-1a27-4d7a-a6a3-ff01cec41fd2\\test\\矢量数据\\Id422801_2022\\Id422801_2022.shp",
	// 						fileSize: "199Mb",
	// 						uploadStatus: 1,
	// 						createTime: "2024-11-13T10:14:52.000+08:00",
	// 						updateTime: "2024-11-13T10:14:52.000+08:00",
	// 						err: null,
	// 						ip: "113.57.78.23",
	// 						type: "2",
	// 						shpServiceUrl: "http://113.57.78.20:38041/geoserver/decode/wms",
	// 						tableName: "vector:vector20241113101502",
	// 						bbox: "[109.08569388517155,29.851317969729244,109.97971058526355,30.670416020264756]",
	// 						zipFilePath:
	// 							"W:\\e188ecd6-1a27-4d7a-a6a3-ff01cec41fd2\\test\\矢量数据\\Id422801_2022.zip",
	// 						woodField: "ld2022",
	// 						legendUrl:
	// 							"E:\\\\project\\\\superai\\\\legend\\\\output\\90472b40-bf06-4154-86a1-c1abf3a3e9de.png",
	// 					},
	// 					{
	// 						value: 10006980,
	// 						label: "Id422801_2022.shp",
	// 						id: 10006980,
	// 						fileName: "Id422801_2022.shp",
	// 						fileMd5: "9DB8079A202F269D6486C4B00D9A06EB",
	// 						filePath: "W:\\e188ecd6-1a27-4d7a-a6a3-ff01cec41fd2\\test\\Id422801_2022.shp",
	// 						fileSize: "199Mb",
	// 						uploadStatus: 1,
	// 						createTime: "2024-11-14T18:26:57.000+08:00",
	// 						updateTime: "2024-11-14T18:26:57.000+08:00",
	// 						err: null,
	// 						ip: "113.57.78.23",
	// 						type: "2",
	// 						shpServiceUrl: "http://113.57.78.20:38041/geoserver/decode/wms",
	// 						tableName: "vector:vector20241114182706",
	// 						bbox: "[109.08569388517155,29.851317969729244,109.97971058526355,30.670416020264756]",
	// 						zipFilePath: "W:\\e188ecd6-1a27-4d7a-a6a3-ff01cec41fd2\\test.zip",
	// 						woodField: "ld2020",
	// 						legendUrl:
	// 							"E:\\\\project\\\\superai\\\\legend\\\\output\\2f112826-ec5b-4bde-b010-819250034252.png",
	// 					},
	// 				],
	// 			},
	// 		],
	// 	},
	// ];
	console.log(res, "left_popup");
});
</script>

<style lang="scss" scoped>
/* 解译任务创建弹窗 */
.ai-popup {
	// @apply fixed z-20;
	// width: 348px;
	// right: 20px;
	// top: 86px;
	// background: rgba(3, 18, 34, 0.9);
	// border-radius: 4px;
	@apply absolute z-20;
	width: 334px;
	// height: 75vh;
	height: calc(100% - 70px);
	// left: 70px;
	background: linear-gradient(180deg, rgba(1, 12, 18, 0.9) 0%, rgba(4, 36, 70, 0.9) 100%);
	border-radius: 4px;
	opacity: 1;
	border: 1px solid #76c6ff;
	transition: all 0.5s;
	.hidden-btn {
		@apply absolute bottom-0 left-full top-0 m-auto cursor-pointer;
		width: 21px;
		height: 97px;
		background-image: url("@img/main/hidden-on.png");
	}
	&.hidden-pannel {
		transform: translateX(-332px);
	}
	&.hidden-pannel .hidden-btn {
		background-image: url("@img/main/hidden-off.png");
	}
}
.form-container {
	--el-text-color-regular: #fff;
	@apply px-3 py-6;
}
.type-group {
	@apply grid grid-cols-3;
	.el-checkbox {
		@apply w-1/3;
	}
}
.bottom-btn-group {
	@apply flex justify-between;
	> * {
		@apply w-1/2;
	}
}
.noneUpload {
	:deep().el-upload.is-drag {
		display: none !important;
	}
}
</style>
